//
//  JVShopcartFormat.m
//  JVShopcart
//
//  Created by AVGD-Jarvi on 17/3/23.
//  Copyright © 2017年 AVGD-Jarvi. All rights reserved.
//

#import "JVShopcartFormat.h"
#import "JVShopcartBrandModel.h"
#import "MJExtension.h"
#import <UIKit/UIKit.h>

@interface JVShopcartFormat ()

@property (nonatomic, strong) NSMutableArray *shopcartListArray;    /**< 购物车数据源 */

@end

@implementation JVShopcartFormat

//- (void)requestShopcartProductList {
//    //在这里请求数据 当然我直接用本地数据模拟的
//    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"shopcart" ofType:@"plist"];
//    NSMutableArray *dataArray = [NSMutableArray arrayWithContentsOfFile:plistPath];
//    self.shopcartListArray = [JVShopcartBrandModel mj_objectArrayWithKeyValuesArray:dataArray];
//
//    [self jsonFromArr:dataArray];
//
//    //成功之后回调
//    [self.delegate shopcartFormatRequestProductListDidSuccessWithArray:self.shopcartListArray];
//}
- (void)requestShopcartProductList {

   
    
    //在这里请求数据 
    [XJHttpTool requestCartListSuccessH:^(id responseObjc) {
        
        //改bug:最后一个元素删除不掉 不管三七二十一直接清空
        [self.shopcartListArray removeAllObjects];

        NSArray *cartArr = responseObjc[@"data"][@"content"][@"cart"];
        if (cartArr.count) {
            self.shopcartListArray = [JVShopcartBrandModel mj_objectArrayWithKeyValuesArray:cartArr];
        }
        
        [self.delegate shopcartFormatRequestProductListDidSuccessWithArray:self.shopcartListArray];
        
    } failureH:^(NSError *error) {
        XJLog(@"失败:%@",error);
    }];
}

- (void)selectProductAtIndexPath:(NSIndexPath *)indexPath isSelected:(BOOL)isSelected {
    JVShopcartBrandModel *brandModel = self.shopcartListArray[indexPath.section];
    JVShopcartProductModel *productModel = brandModel.goods[indexPath.row];
    productModel.isSelected = isSelected;
    
    BOOL isBrandSelected = YES;
    
    for (JVShopcartProductModel *aProductModel in brandModel.goods) {
        if (aProductModel.isSelected == NO) {
            isBrandSelected = NO;
        }
    }
    
    brandModel.isSelected = isBrandSelected;
    
    [self.delegate shopcartFormatAccountForTotalPrice:[self accountTotalPrice] totalCount:[self accountTotalCount] isAllSelected:[self isAllSelected]];
}

- (void)selectBrandAtSection:(NSInteger)section isSelected:(BOOL)isSelected {
    JVShopcartBrandModel *brandModel = self.shopcartListArray[section];
    brandModel.isSelected = isSelected;
    
    for (JVShopcartProductModel *aProductModel in brandModel.goods) {
        aProductModel.isSelected = brandModel.isSelected;
    }
    
    [self.delegate shopcartFormatAccountForTotalPrice:[self accountTotalPrice] totalCount:[self accountTotalCount] isAllSelected:[self isAllSelected]];
}

- (void)changeCountAtIndexPath:(NSIndexPath *)indexPath count:(NSInteger)count {
    JVShopcartBrandModel *brandModel = self.shopcartListArray[indexPath.section];
    JVShopcartProductModel *productModel = brandModel.goods[indexPath.row];
    if (count <= 0) {
        count = 1;
    } else if (count > productModel.productStocks) {
        count = productModel.productStocks;
    }
    
    //根据请求结果决定是否改变数据
//    productModel.productQty = count;
    productModel.quantity = count;
    [self.delegate shopcartFormatAccountForTotalPrice:[self accountTotalPrice] totalCount:[self accountTotalCount] isAllSelected:[self isAllSelected]];
}

- (void)deleteProductAtIndexPath:(NSIndexPath *)indexPath {
    JVShopcartBrandModel *brandModel = self.shopcartListArray[indexPath.section];
    JVShopcartProductModel *productModel = brandModel.goods[indexPath.row];
    
    //根据请求结果决定是否删除
    [brandModel.goods removeObject:productModel];
    if (brandModel.goods.count == 0) {
        [self.shopcartListArray removeObject:brandModel];
    } else {
        if (!brandModel.isSelected) {
            BOOL isBrandSelected = YES;
            for (JVShopcartProductModel *aProductModel in brandModel.goods) {
                if (!aProductModel.isSelected) {
                    isBrandSelected = NO;
                    break;
                }
            }
            
            if (isBrandSelected) {
                brandModel.isSelected = YES;
            }
        }
    }
    
    [self.delegate shopcartFormatAccountForTotalPrice:[self accountTotalPrice] totalCount:[self accountTotalCount] isAllSelected:[self isAllSelected]];
    
    if (self.shopcartListArray.count == 0) {
        [self.delegate shopcartFormatHasDeleteAllProducts];
    }
}

- (void)beginToDeleteSelectedProducts {
    NSMutableArray *selectedArray = [[NSMutableArray alloc] init];
    for (JVShopcartBrandModel *brandModel in self.shopcartListArray) {
        for (JVShopcartProductModel *productModel in brandModel.goods) {
            if (productModel.isSelected) {
                [selectedArray addObject:productModel];
            }
        }
    }
    
    [self.delegate shopcartFormatWillDeleteSelectedProducts:selectedArray];
}

- (void)deleteSelectedProducts:(NSArray *)selectedArray {
    
    XJLog(@"%@",selectedArray);
    
    [self rb_requestDeleteCart:selectedArray];
    
}


//- (void)deleteSelectedProducts:(NSArray *)selectedArray {
//    //网络请求
//    //根据请求结果决定是否批量删除
//    NSMutableArray *emptyArray = [[NSMutableArray alloc] init];
//    for (JVShopcartBrandModel *brandModel in self.shopcartListArray) {
//        [brandModel.goods removeObjectsInArray:selectedArray];
//
//        if (brandModel.goods.count == 0) {
//            [emptyArray addObject:brandModel];
//        }
//    }
//
//    if (emptyArray.count) {
//        [self.shopcartListArray removeObjectsInArray:emptyArray];
//    }
//
//    [self.delegate shopcartFormatAccountForTotalPrice:[self accountTotalPrice] totalCount:[self accountTotalCount] isAllSelected:[self isAllSelected]];
//
//    if (self.shopcartListArray.count == 0) {
//        [self.delegate shopcartFormatHasDeleteAllProducts];
//    }
//}

- (void)starProductAtIndexPath:(NSIndexPath *)indexPath {
    //这里写收藏的网络请求
    
}

- (void)starSelectedProducts {
    //这里写批量收藏的网络请求
    
}

- (void)selectAllProductWithStatus:(BOOL)isSelected {
    for (JVShopcartBrandModel *brandModel in self.shopcartListArray) {
        brandModel.isSelected = isSelected;
        for (JVShopcartProductModel *productModel in brandModel.goods) {
            productModel.isSelected = isSelected;
        }
    }
    
    [self.delegate shopcartFormatAccountForTotalPrice:[self accountTotalPrice] totalCount:[self accountTotalCount] isAllSelected:[self isAllSelected]];
}

- (void)settleSelectedProducts {
    NSMutableArray *settleArray = [[NSMutableArray alloc] init];
    for (JVShopcartBrandModel *brandModel in self.shopcartListArray) {
        NSMutableArray *selectedArray = [[NSMutableArray alloc] init];
        for (JVShopcartProductModel *productModel in brandModel.goods) {
            if (productModel.isSelected) {
                [selectedArray addObject:productModel];
            }
        }
    
        brandModel.selectedArray = selectedArray;
        
        if (selectedArray.count) {
            [settleArray addObject:brandModel];
        }
    }
    
    [self.delegate shopcartFormatSettleForSelectedProducts:settleArray];
}

#pragma mark private methods

- (float)accountTotalPrice {
    float totalPrice = 0.f;
    for (JVShopcartBrandModel *brandModel in self.shopcartListArray) {
        for (JVShopcartProductModel *productModel in brandModel.goods) {
            if (productModel.isSelected) {
                totalPrice += productModel.price * productModel.quantity;
//                totalPrice += productModel.productPrice * productModel.productQty;
            }
        }
    }
    
    return totalPrice;
}

- (NSInteger)accountTotalCount {
    NSInteger totalCount = 0;
    
    for (JVShopcartBrandModel *brandModel in self.shopcartListArray) {
        for (JVShopcartProductModel *productModel in brandModel.goods) {
            if (productModel.isSelected) {
//                totalCount += productModel.productQty;
                totalCount += productModel.quantity;
            }
        }
    }
    
    return totalCount;
}

- (BOOL)isAllSelected {
    if (self.shopcartListArray.count == 0) return NO;
    
    BOOL isAllSelected = YES;
    
    for (JVShopcartBrandModel *brandModel in self.shopcartListArray) {
        if (brandModel.isSelected == NO) {
            isAllSelected = NO;
        }
    }
    
    return isAllSelected;
}


#pragma mark - 网络请求
- (void)rb_requestDeleteCart:(NSArray <JVShopcartProductModel *>*)goodsArr {
    
    NSMutableString *mStr = [NSMutableString string];
    for (JVShopcartProductModel *productM in goodsArr) {
        [mStr appendFormat:@"%@,",productM.cart_id];
    }
    
    XJLog(@"======:%@",mStr);
    
    [XJHttpTool requestDeleteCartWithIdsStr:mStr successH:^(id responseObjc) {
        XJLog(@"%@",responseObjc);
        //如果删除成功:重新调用一次总接口刷新数据。
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            //
            [self requestShopcartProductList];
            
        }else {
            [JRToast showWithText:responseObjc[@"message"]];
        }
        
    } failH:^(NSError *error) {
        XJLog(@"%@",error);
    }];
}

#pragma mark - arr 转JSON
- (void)jsonFromArr:(NSArray *)arr {
    if (arr.count) {
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        XJLog(@"%@",jsonStr);
    }else {
        XJLog(@"数据为空");
    }
}

- (void)jsonFromDic:(NSDictionary *)dic {
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    
    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    XJLog(@"%@",jsonStr);
}
@end
